﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using PraxisRent.Entities;
using PraxisRent.BL;
using Microsoft.Practices.Unity;

namespace PraxisRent.UI
{
    public partial class FrmCredito : Form
    {
        [Dependency]
        public ICreditoBL creditoBL { get; set; }

        [Dependency]
        public IPagoBL pagoBL { get; set; }

        [Dependency]
        public IAlquilerBL alquilerBL { get; set; }

        [Dependency]
        public IClienteJuridicoBL cliJuriBL { get; set; }

        [Dependency]
        public IClienteNaturalBL cliNatBL { get; set; }

        [Dependency]
        public IUsuarioMenuBL usuMenuBL { get; set; }

        public FrmCredito()
        {
            InitializeComponent();
            this.BuilUp();
        }

        public ALQUILER _currentAlquiler { get; set; }


        public void CargaDataByAlquiler()
        {
            cREDITOBindingSource.DataSource = creditoBL.GetAllFromCreditoByAlquiler(_currentAlquiler.Codigo);
            if (cREDITOBindingSource.Count == 0)
                {
                    MessageBox.Show("Credito no existente.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
        }

        public USUARIO currentUsuarioCredito { get; set; }

        private void FrmCredito_Load(object sender, EventArgs e)
        {
            if (currentUsuarioCredito != null)
            {
                menuLlena();
            }
            //else
            //    cargaData();
        }

        public void menuLlena()
        {
            var datoUsuario = usuMenuBL.GetAllFromUsuarioByPersonaFromLogin(currentUsuarioCredito.PERSONA.Dni);

            var permisos = (from c in usuMenuBL.GetAllFromUsuarioMenuByMenuId(datoUsuario.UsuarioId)
                            select c.MENU.Tag.ToString()).ToArray();

            System.Windows.Forms.Button[] botones = new System.Windows.Forms.Button[] { 
            this.btnNuevo,this.btnPagar};

            //obtengo todos los PERMISOS NO ASIGNADOS al usuario
            var noVisible = from nv in botones
                            where !permisos.Contains(nv.Tag.ToString())
                            select nv;

            //coloco DESABILITADO a los permisos no asignados
            noVisible.ToList().ForEach(nv => nv.Enabled = false);

            cargaData();
        }

        public void cargaData()
        {
            cREDITOBindingSource.DataSource = creditoBL.GetAllFromCredito();
        }

        private void btnBuscar_Click(object sender, EventArgs e)
        {
            if (rbtnCliente.Checked == true)
            {
                cREDITOBindingSource.DataSource = creditoBL.GetAllFromCreditoByCliente(TxtCriterio.Text);
                if (cREDITOBindingSource.Count == 0)
                {
                    MessageBox.Show("Credito no existente.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else if (rbtnAlquiler.Checked == true)
            {
                cREDITOBindingSource.DataSource = creditoBL.GetAllFromCreditoByAlquiler(Int32.Parse(TxtCriterio.Text));
                if (cREDITOBindingSource.Count == 0)
                {
                    MessageBox.Show("Credito no existente.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private void TxtCriterio_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (rbtnCliente.Checked == true)
                {
                    cREDITOBindingSource.DataSource = creditoBL.GetAllFromCreditoByCliente(TxtCriterio.Text);
                    if (cREDITOBindingSource.Count == 0)
                    {
                        MessageBox.Show("Credito no existente.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else if (rbtnAlquiler.Checked == true)
                {
                    cREDITOBindingSource.DataSource = creditoBL.GetAllFromCreditoByAlquiler(Int32.Parse(TxtCriterio.Text));
                    if (cREDITOBindingSource.Count == 0)
                    {
                        MessageBox.Show("Credito no existente.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
        }

        private void TxtCriterio_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (rbtnCliente.Checked == true)
            {
                if (Char.IsLetter(e.KeyChar))
                {
                    e.Handled = false;
                }
                else if (Char.IsControl(e.KeyChar))
                {
                    e.Handled = false;
                }
                else if (Char.IsSeparator(e.KeyChar))
                {
                    e.Handled = false;
                }
                else
                {
                    e.Handled = true;
                }
            }
            else if (rbtnAlquiler.Checked == true)
            {
                if (Char.IsNumber(e.KeyChar))
                {
                    e.Handled = false;
                }
                else if (Char.IsControl(e.KeyChar))
                {
                    e.Handled = false;
                }
                else if (Char.IsSeparator(e.KeyChar))
                {
                    e.Handled = false;
                }
                else
                {
                    e.Handled = true;
                }
            }
        }

        private void cREDITORadGridView_CurrentCellChanged(object sender, Telerik.WinControls.UI.CurrentCellChangedEventArgs e)
        {
            var currentCredito = cREDITOBindingSource.Current as CREDITO;

            List<PAGO> listPagosCancelados = pagoBL.GetAllFromPagoByIdCreditoAndCancelados(currentCredito.Id);
            decimal suma = 0;

            if (currentCredito != null)
            {
                pAGOBindingSource.DataSource = pagoBL.GetAllFromPagoByIdCredito(currentCredito.Id);

                #region Cliente
                try
                {
                    for (int count = 0; count < cREDITORadGridView.Rows.Count; count++)
                    {
                        if (currentCredito != null)
                        {
                            //ALQUILER a = cREDITORadGridView.Rows[count].Cells[1].Value as ALQUILER;
                            ALQUILER a = (from c in alquilerBL.GetAllFromAlquiler()
                                                where c.Codigo.Equals(currentCredito.CodigoAlquiler)
                                          select c).SingleOrDefault();
                            var cliJuri = (from c in cliJuriBL.GetAllFromClienteJuridico()
                                           where c.ClienteJuridicoId.Equals(a.CodigoCliente)
                                           select c).SingleOrDefault();
                            var cliNat = (from c in cliNatBL.GetAllFromClienteNatural()
                                          where c.ClienteNaturalId.Equals(a.CodigoCliente)
                                          select c).SingleOrDefault();

                            if (cliJuri != null)
                            {
                                cREDITORadGridView.Rows[count].Cells[2].Value = cliJuri.RazonSocial.ToString();
                            }
                            else if (cliNat != null)
                            {
                                cREDITORadGridView.Rows[count].Cells[2].Value = cliNat.NombreCompleto.ToString();
                            }
                            lblTotal.Text = Convert.ToString(currentCredito.Total);
                        }
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("Error");
                }
                #endregion

                #region Pagos
                if (listPagosCancelados.Count != 0)
                {
                    foreach (var item in listPagosCancelados)
                    {
                        suma = suma + item.Abono ?? default(decimal);
                    }
                }
                decimal sumaRedondeada = decimal.Round(suma, 0);
                lblTPagado.Text = Convert.ToString(sumaRedondeada);

                decimal deuda = Convert.ToDecimal(lblTotal.Text) - Convert.ToDecimal(lblTPagado.Text);
                decimal deudaRedondeada = decimal.Round(deuda, 0);
                lblDeuda.Text = Convert.ToString(deudaRedondeada);
                #endregion
            }
        }

        private void pAGODataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // verificamos si se hace click en l BOTON PAGAR
            if (this.pAGODataGridView.Columns[e.ColumnIndex].Name.Equals("Pagar"))
            {
                var currentPago = pAGOBindingSource.Current as PAGO;

                FrmMttoPago frm = new FrmMttoPago();
                frm._currentPago = currentPago;
                frm.pagarPago();
                frm.ShowDialog();
            }
        }

        private void cREDITORadGridView_Click(object sender, EventArgs e)
        {
            var currentCredito = cREDITOBindingSource.Current as CREDITO;

            List<PAGO> listPagosCancelados = pagoBL.GetAllFromPagoByIdCreditoAndCancelados(currentCredito.Id);
            decimal suma = 0;

            #region Cliente
            try
            {
                for (int count = 0; count < cREDITORadGridView.Rows.Count; count++)
                {
                    if (currentCredito != null)
                    {
                        //ALQUILER a = cREDITORadGridView.Rows[count].Cells[1].Value as ALQUILER;
                        ALQUILER a = (from c in alquilerBL.GetAllFromAlquiler()
                                                where c.Codigo.Equals(currentCredito.CodigoAlquiler)
                                      select c).SingleOrDefault();
                        var cliJuri = (from c in cliJuriBL.GetAllFromClienteJuridico()
                                       where c.ClienteJuridicoId.Equals(a.CodigoCliente)
                                       select c).SingleOrDefault();
                        var cliNat = (from c in cliNatBL.GetAllFromClienteNatural()
                                      where c.ClienteNaturalId.Equals(a.CodigoCliente)
                                      select c).SingleOrDefault();

                        if (cliJuri != null)
                        {
                            cREDITORadGridView.Rows[count].Cells[2].Value = cliJuri.RazonSocial.ToString();
                        }
                        else if (cliNat != null)
                        {
                            cREDITORadGridView.Rows[count].Cells[2].Value = cliNat.NombreCompleto.ToString();
                        }
                        lblTotal.Text = Convert.ToString(currentCredito.Total);
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Error");
            }
            #endregion

            #region Pagos
            if (listPagosCancelados.Count != 0)
            {
                foreach (var item in listPagosCancelados)
                {
                    suma = suma + item.Abono ?? default(decimal);
                }
            }
            decimal sumaRedondeada = decimal.Round(suma, 0);
            lblTPagado.Text = Convert.ToString(sumaRedondeada);

            decimal deuda = Convert.ToDecimal(lblTotal.Text) - Convert.ToDecimal(lblTPagado.Text);
            decimal deudaRedondeada = decimal.Round(deuda, 0);
            lblDeuda.Text = Convert.ToString(deudaRedondeada);
            #endregion
        }

        private void btnNuevo_Click(object sender, EventArgs e)
        {
            FrmMttoCredito frm = new FrmMttoCredito();
            frm.NuevoCredito();
            frm.ShowDialog();
        }

        private void btnPagar_Click(object sender, EventArgs e)
        {
            var credito = cREDITOBindingSource.Current as CREDITO;
            List<PAGO> listPago = new List<PAGO>();

            if (credito != null)
            {
                var rpt = MessageBox.Show(this, string.Format("¿Desea Pagar todas las Cuotas?"), "Pagar", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (rpt == DialogResult.Yes)
                {
                    FrmDescripcionPago frm = new FrmDescripcionPago();
                    frm.ShowDialog();
                    if (frm.currentPago != null)
                    {
                            listPago = (from c in pagoBL.GetAllFromPagoByIdCredito(credito.Id)
                                        where c.Cancelado == false
                                        select c).ToList();

                            foreach (var item in listPago)
                            {
                                item.Cancelado = true;
                                item.Descripcion = frm.currentPago.Descripcion.ToUpper();
                                item.FechaPago = DateTime.Now;
                                item.NumComprobante = frm.currentPago.NumComprobante.ToUpper();
                                pagoBL.UpdatePago(item);
                            }
                        credito.Cancelado = true;
                        creditoBL.UpdateCredito(credito);
                    
                        MessageBox.Show("Registro Correcto ", "Registro",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);

                        if (_currentAlquiler != null)
                        {
                            CargaDataByAlquiler();
                        }
                        else
                        {
                            cargaData();
                        }
                    }
                }
             }
            else
            {
                MessageBox.Show("Debe seleccionar un Credito.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

    }
}
